<template>
  <div v-if="windowSetInfo && windowSetInfo.isOpen && windowSetInfo.isOpen != -1 && isVisitor != 1 && !isKpStudyWxApp">
    <transition name="fade-translate-x">
      <div class="c-pf c-pz100 c-p-r0 c-mr24 c-p-r0 coms-live-iframe-hide" :class="type==9?'c-p-b280':'c-p-b160'" v-show="(windowSetInfo.type == 1) || (windowSetInfo.type == 2 && !isSrcoll)">
        <!-- 子窗口独立入口展示 -->
        <div v-for="(item, index) in independentList" :key="index">
          <div class="c-ww72 c-hh72 c-flex-row c-flex-center c-p boxShadow c-bg-white c-mt20 c-brp50 c-text-hidden"
            @click="clickIcon(item.name)"
          >
            <div class="iconfont c-fc-xblack" :class="item.name == 'home' ? 'c-fs32' : 'c-fs34'" v-if="item.imgUrl == ''" v-html="iconMap[item.name]"></div>
            <img class="c-w100 c-h c-brp50" :src="item.imgUrl" v-if="item.imgUrl">
          </div>
        </div>
        <!-- 子窗口非独立独立入口展示 -->
        <template v-if="unIndependentList.length < 2">
          <div v-for="(item, index) in unIndependentList" :key="index">
            <div class="c-ww72 c-hh72 c-flex-row c-flex-center c-p boxShadow c-bg-white c-mt20 c-brp50 c-text-hidden"
              @click="clickIcon(item.name)"
            >
              <div class="iconfont c-fc-xblack" :class="item.name == 'home' ? 'c-fs32' : 'c-fs34'" v-if="item.imgUrl == ''" v-html="iconMap[item.name]"></div>
              <img class="c-w100 c-h c-brp50" :src="item.imgUrl" v-if="item.imgUrl">
            </div>
          </div>
        </template>
        <!-- 收起展开 -->
        <template v-if="unIndependentList.length > 1">
          <div class="c-p c-mt20">
            <div class="c-ww72 c-hh72 c-p boxShadow c-brp50 c-text-hidden zoomBtn" :class="[!zoomIn && !windowSetInfo.menuBtn.closeImg ? 'c-bg-gray' : 'c-bg-white', !zoomIn ? 'animate' : '']" @click.stop="toggleZoom">
              <transition name="fade-opacity">
                <div class="c-w100 c-h c-pa c-p-l0 c-p-t0" v-show="zoomIn">
                  <img class="c-w100 c-h c-lh72 c-textAlign-c c-brp50" :src="windowSetInfo.menuBtn.openImg" v-if="windowSetInfo.menuBtn.openImg">
                  <div v-else class="c-w100 c-h c-lh72 c-textAlign-c iconfont c-fs34 c-fc-xblack">&#xe727;</div>
                </div>
              </transition>
              <transition name="fade-opacity">
                <div class="c-w100 c-h c-pa c-p-l0 c-p-t0" v-show="!zoomIn">
                  <img class="c-w100 c-h c-lh72 c-textAlign-c c-brp50" :src="windowSetInfo.menuBtn.closeImg" v-if="windowSetInfo.menuBtn.closeImg">
                  <div v-else class="c-w100 c-h c-lh72 c-textAlign-c iconfont c-fs34 c-fc-white">&#xeca0;</div>
                </div>
              </transition>
            </div>
            <!-- 子窗口非独立入口展示 -->
            <div ref="contentBox" class="c-flex-row c-aligni-center c-p-r88 c-bg-white c-br16 fadeOpacityLeft box c-pa c-pl4" :class="unIndependentList.length > 3 ? 'c-flexw-wrap c-ww312 topCenter2' : 'mw312 topCenter1'" v-show="showUnIndependentList">
              <div v-for="(item, index) in unIndependentList" :key="index" class="c-pv16">
                <div class="c-flex-column c-flex-center c-p c-ww44 c-text-hidden c-ww100 c-ph8"
                  @click="clickIcon(item.name)"
                >
                  <div class="c-ww40 c-hh40 c-lh40 c-textAlign-c iconfont c-fc-xblack" :class="item.name == 'home' ? 'c-fs32' : 'c-fs34'" v-if="item.imgUrl == ''" v-html="iconMap[item.name]"></div>
                  <img class="c-ww40 c-hh40 c-brp50" :src="item.imgUrl" v-if="item.imgUrl">
                  <span class="c-fs20 c-fc-sblack c-textAlign-c c-mt16">{{item.title}}</span>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </transition>
    <connect-serves :customerConf="customerConf" :showModal="showConnectServerModal" @closeModal="closeModal"></connect-serves>
  </div>
</template>
<script>
import { appRouterChange } from "@/mixin/appRouterPush.js";
import { utilJs } from "@/utils/common.js";
import ConnectServes from "@/components/templates/common/connectServes.vue";
export default {
  name: 'suspensionGroupCom',
  mixins: [appRouterChange],
  props: {
    suspensionGroupSet: {
      type: Object,
      default: () => {
        return null
      },
    },
  },
  components: {
    ConnectServes
  },
  data() {
    return {
      zoomIn: true,
      visiableIconNum: 0,
      companyAuth: localStorage.getItem("companyAuth") ? JSON.parse(localStorage.getItem("companyAuth")) : null,
      customerConf: localStorage.getItem("customerConf") ? JSON.parse(localStorage.getItem("customerConf")) : null, // h5客服信息配置
      customerConfMp: localStorage.getItem("customerConfMp") ? JSON.parse(localStorage.getItem("customerConfMp")) : null, // 小程序客服信息配置
      showConnectServerModal: false, //客服
      iconMap: {
        'shopCart': '&#xe637;',
        'service': '&#xe686;',
        'backtop': '&#xe683;',
        'home': '&#xe659;',
        'my': '&#xe647;'
      },
      visibleList: [],
      isCustServiceOpen: localStorage.getItem("isCustServiceOpen") == 1 ? true : false, // 是否开启小程序客服
      showUnIndependentList: false,
      isVisitor: localStorage.getItem("isVisitor") || 0, //1是游客
      isSrcoll: false, // 判断页面是否在滚动
      timer: null, // 记录滚动得定时器
      currentTop: 0, // 当前页面滚动高度
      type: 0, // 1、微页面  3.店铺主页, 4.个人中心页 5、课程, 6.专栏, 7.训练营, 8.知识套餐, 9.公开课, 10.实体商品, 11.打卡, 12.活动
      windowSetInfo: null, // 组件内容
      mId: '', // 微页面id
    };
  },
  computed: {
    independentList() {
      return this.visibleList ? this.visibleList.filter(item => item.independent == true) : [];
    },
    unIndependentList() {
      return this.visibleList ? this.visibleList.filter(item => item.independent == false) : [];
    },
    // 判断是否显示套壳小程序
    isKpStudyWxApp() {
      return sessionStorage.getItem("isKpStudy") ? sessionStorage.getItem("isKpStudy") == 1 : false;
    },
  },
  watch: {
    suspensionGroupSet: {
      handler(newVal) {
        this.windowSetInfo = null;
        this.type = 0;
        this.mId = '';
        if (newVal) this.publicInitData(newVal);
      },
      deep: true,
      immediate: true, // 页面加载立即执行
    }
  },
  methods: {
    // 组件初始化
    publicInitData(data) {
      this.type = data.type || 0;
      this.mId = data.mId || '';
      if (this.type > 0) {
        this.getWindowsSet();
      }
    },
    // 获取悬浮窗组件数据
    getWindowsSet() {
      if (this.windowSetInfo) return
      let path = `${global.apiurl}OaIndex/getWindowsSet?type=${this.type}${this.mId ? '&pageId=' + this.mId : ''}`
      utilJs.getMethod(path, (res) => {
        if (res && res.isOpen && res.isOpen == -1) {
          this.windowSetInfo = null;
          return
        }
        this.windowSetInfo = res;
        if (this.windowSetInfo.content && this.windowSetInfo.content.length > 0) {
          let visibleList = [];
          this.windowSetInfo.content.forEach(item => {
            if (this.getItemVisible(item)) {
              visibleList.push(item);
            }
          })
          this.visibleList = visibleList;
          if (this.windowSetInfo && this.windowSetInfo.customerConf && this.windowSetInfo.customerConfMp) {
            this.customerConf = this.windowSetInfo.customerConf;
            this.customerConfMp = this.windowSetInfo.customerConfMp;
          }
          this.showUnIndependentList = false;
          this.zoomIn = true;
          // 用来判断组件暂用页面右边的悬浮图标数量
          let unIndependent = visibleList.filter(item => item.independent == false);
          let independent = visibleList.filter(item => item.independent == true);
          let iconNum = unIndependent.length > 0 ? independent.length + 1 : independent.length;
          this.$store.commit('updateRightSuspensionIconNum', iconNum);
        }
      })
    },
    getItemVisible(item) {
      let serviceEnable = (!this.$isWxApp() && (this.customerConf && this.customerConf.enableCustomer == 1)) || (this.$isWxApp() && (this.customerConfMp && this.customerConfMp.enableCustomer == 1));
      let mallEnable = this.companyAuth && this.companyAuth.enableMallModule == 1;
      if ((item.permission != 3 && (item.name != 'shopCart' && item.name != 'service')) || (item.name == 'shopCart' && !mallEnable) || (item.name == 'service' && !serviceEnable)) {
        return false
      }
      return item.enable
    },
    onScroll() {
      this.isSrcoll = true;
      this.timer && clearTimeout(this.timer);
      this.showUnIndependentList = false;
      this.zoomIn = true;
      this.timer = setTimeout(() => {
        this.handleScrollEnd();
      }, 500);
      this.currentTop = document.documentElement.scrollTop || document.body.scrollTop;
    },
    handleScrollEnd() {
      let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop == this.currentTop) {
        this.isSrcoll = false;
        clearTimeout(this.timer);
      }
    },
    clickIcon(name) {
      this.showUnIndependentList = false;
      this.zoomIn = true;
      if (name == 'shopCart') {
        this.$routerGo(this, "push", { path: "/mall/shopCart/shopCart" });
      } else if (name == 'service') {
        this.custServiceFun();
      } else if (name == 'backtop') {
        this.$nextTick(() => {
          let upRoll = setInterval(() => {
            let top = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop // 获取多个值 是防止安卓获取不到对应得top
            console.log('top:' + top);
            let speed = Math.ceil(top / 10) // 每次滚动多少 （步长值）
            if (top > 0) {
              window.scrollTo(0, top -= speed);
            } else {
              clearInterval(upRoll) // 回到顶部清除定时器
            }
          }, 20)
        })
      } else if (name == 'home') {
        this.$routerGo(this, "push", { path: "/" });
      } else if (name == 'my') {
        this.$routerGo(this, "push", { path: "/member/memberIndex" });
      }
    },
    toggleZoom() {
      this.zoomIn = !this.zoomIn;
      this.showUnIndependentList = !this.showUnIndependentList;
      let num = 0;
      if (this.independentList.length > 0 && this.unIndependentList.length == 0) {
        num = this.independentList.length ;
      } else {
        num = this.independentList.length + 1
      }
      if (this.type == 1 || this.type == 3) {
        this.$store.commit('updateRightSuspensionIconNum', num);
      }
    },
    closeModal() {
      this.showConnectServerModal = false;
    },
    custServiceFun() {
      let service = this.$isWxApp() ? this.customerConfMp.guideType : this.customerConf.guideType;
      // 小程序 1.小程序在线客服，2.微信客服
      if (this.$isWxApp()) {
        if (service == 1) { // 在线客服特殊处理
          utilJs.miniProgramGoTo("push", "/pages/member/contact/index");
        } else if (service == 2) {
          utilJs.miniProgramGoTo("push", `/pages/member/contact/index?customerLink=${encodeURIComponent(this.customerConfMp.customerLink)}&corpId=${this.customerConfMp.corpId}`);
        }
      } else {
        // h5弹窗 1.引导弹窗，2.创匠客服，3.微信客服
        if (service == 1) {
           this.showConnectServerModal = true;
          return;
        }
        if (service == 2) {
          let host = window.location.host.indexOf("kptest.ckjr001.com") > -1 ? 'lingting-cs.myckjr.com' : window.location.host.indexOf("formal.ckjr001.com") > -1 ? 'lingting-formal.myckjr.com' : 'lingting.ckjr001.com';
          let url = "http://" + host + "/?#/?token=" + localStorage.getItem("token") + '&srcSys=kp'
          let newApp = utilJs.getAppVersion() > 0;
          //新App外链的话走原生跳转
          if (newApp) {
            this.iosAppRouteChange(url);
            return;
          }
          window.location.href = url;
        } else if (service == 3) {
          window.location.href = this.customerConf.customerLink;
        } else if (service == 4) {
          this.$routerGo(this, "push", { path: `/homePage/aiAssistant/aiAssistantChat?subScene=1` });
        }
      }
    },
    hideBox(e) {
      // 判断是否点击需隐藏的 div 及其内部元素
      if (this.$refs.contentBox && !this.$refs.contentBox.contains(e.target)) {
        this.showUnIndependentList = false;
        this.zoomIn = true;
      }
    },
  },
  mounted() {
    this.isSrcoll = false;
    this.showUnIndependentList = false;
    this.windowSetInfo = null;
    this.$nextTick(() => {
      window.addEventListener("scroll", this.onScroll);
      document.addEventListener('click', this.hideBox);
    })
  },
  activated() {
  },
  beforeDestroy() {
    document.removeEventListener('click', this.hideBox);
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScroll);
  }
}
</script>
<style scoped>
.boxShadow {
  box-shadow: 0 0 6px 0 rgba(0,0,0,0.18);
}
.c-maxh36 {
  max-height: 0.9rem;
}
.zoomBtn {
  transition: all .3s linear;
}
.animate {
  transform: rotate(360deg);
}
.box {
  box-shadow: 0 0 10px 0 rgba(0,0,0,0.18);
}
.box::after {
  position: absolute;
  content: "";
  border-left: 0.4rem solid #ffffff;
  border-top: 0.25rem solid transparent;
  border-bottom: 0.25rem solid transparent;
  right: -0.3rem;
  top: calc(50% - 0.4rem);
  z-index: 10;
}
.mw312 {
  max-width: 7.8rem;
}
.fadeOpacityLeft {
  animation: showOpacityLft 0.5s forwards;
}
@keyframes showOpacityLft {
  from {
    opacity: 0;
    transform: translateX(10%);
  }
  to {
    opacity: 1;
    transform: translateX(0%);
  }
}
.topCenter1 {
  top: calc(50% - 1.3rem);
}
.topCenter2 {
  top: calc(50% - 2.7rem);
}
/* 弹窗从下往上动画 */
.fade-translate-x-enter-active{
  animation: showTranslateX 0.5s forwards;
}
.fade-translate-x-leave-active{
  animation: hideTranslateX 0.5s forwards;
}
@keyframes showTranslateX {
  from {
    transform: translateX(2rem);
    opacity: 1;
  }
  to {
    transform: translateX(0);
    opacity: 0.5;
  }
}
@keyframes hideTranslateX {
  from {
    transform: translateX(0);
    opacity: 0.5;
  }
  to {
    transform: translateX(2rem);
    opacity: 1;
  }
}
</style>